import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import departmentService from '../services/departmentService';
import './AdminDepartmentManagementPage.css';

const AdminDepartmentManagementPage = () => {
    const [departments, setDepartments] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [currentDepartment, setCurrentDepartment] = useState({ id: null, name: '', description: '' });
    const [isEditing, setIsEditing] = useState(false);
    
    const navigate = useNavigate();

    // 加载所有科室
    useEffect(() => {
        fetchDepartments();
    }, []);

    const fetchDepartments = async () => {
        try {
            setLoading(true);
            const data = await departmentService.getAllDepartments();
            setDepartments(data);
            setError(null);
        } catch (err) {
            setError('获取科室列表失败: ' + (err.response?.data?.message || err.message));
        } finally {
            setLoading(false);
        }
    };

    const handleOpenAddModal = () => {
        setCurrentDepartment({ id: null, name: '', description: '' });
        setIsEditing(false);
        setIsModalOpen(true);
    };

    const handleOpenEditModal = (department) => {
        setCurrentDepartment({
            id: department.id,
            name: department.name,
            description: department.description
        });
        setIsEditing(true);
        setIsModalOpen(true);
    };

    const handleCloseModal = () => {
        setIsModalOpen(false);
    };

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setCurrentDepartment({ ...currentDepartment, [name]: value });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        
        try {
            if (isEditing) {
                await departmentService.updateDepartment(currentDepartment.id, currentDepartment);
            } else {
                await departmentService.createDepartment(currentDepartment);
            }
            
            // 刷新科室列表
            fetchDepartments();
            handleCloseModal();
        } catch (err) {
            setError((isEditing ? '更新' : '创建') + '科室失败: ' + 
                (err.response?.data?.message || err.message));
        }
    };

    const handleDelete = async (id) => {
        if (window.confirm('确定要删除这个科室吗？')) {
            try {
                await departmentService.deleteDepartment(id);
                // 刷新科室列表
                fetchDepartments();
            } catch (err) {
                setError('删除科室失败: ' + (err.response?.data?.message || err.message));
            }
        }
    };

    const handleBack = () => {
        navigate('/admin/dashboard');
    };

    return (
        <div className="admin-department-management">
            <h2>科室管理</h2>
            
            {error && <div className="error">{error}</div>}
            
            <div className="action-bar">
                <button className="add-department-btn" onClick={handleOpenAddModal}>
                    添加新科室
                </button>
                <button className="back-btn" onClick={handleBack}>
                    返回管理面板
                </button>
            </div>
            
            {loading ? (
                <div className="loading">加载科室列表中...</div>
            ) : departments.length === 0 ? (
                <div className="no-departments">暂无科室数据</div>
            ) : (
                <table className="departments-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>名称</th>
                            <th>描述</th>
                            <th>创建时间</th>
                            <th>更新时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {departments.map(department => (
                            <tr key={department.id}>
                                <td>{department.id}</td>
                                <td>{department.name}</td>
                                <td>{department.description}</td>
                                <td>{new Date(department.createdAt).toLocaleString()}</td>
                                <td>{new Date(department.updatedAt).toLocaleString()}</td>
                                <td>
                                    <button 
                                        className="edit-btn" 
                                        onClick={() => handleOpenEditModal(department)}
                                    >
                                        编辑
                                    </button>
                                    <button 
                                        className="delete-btn" 
                                        onClick={() => handleDelete(department.id)}
                                    >
                                        删除
                                    </button>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            )}
            
            {/* 添加/编辑科室的模态框 */}
            {isModalOpen && (
                <div className="modal-overlay">
                    <div className="modal-content">
                        <h3>{isEditing ? '编辑科室' : '添加新科室'}</h3>
                        <form onSubmit={handleSubmit}>
                            <div className="form-group">
                                <label htmlFor="name">科室名称</label>
                                <input
                                    type="text"
                                    id="name"
                                    name="name"
                                    value={currentDepartment.name}
                                    onChange={handleInputChange}
                                    required
                                />
                            </div>
                            <div className="form-group">
                                <label htmlFor="description">科室描述</label>
                                <textarea
                                    id="description"
                                    name="description"
                                    value={currentDepartment.description || ''}
                                    onChange={handleInputChange}
                                />
                            </div>
                            <div className="form-actions">
                                <button type="button" className="cancel-btn" onClick={handleCloseModal}>
                                    取消
                                </button>
                                <button type="submit" className="submit-btn">
                                    {isEditing ? '更新' : '创建'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default AdminDepartmentManagementPage; 